package com.hundsun.aitest.service.impl;
/**
 * @author ：lijk34925
 * @date ：Created in 2020/10/20 15:25
 * @description：Yapi接口操作
 * @modified By：
 * @version: $version$
 */

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONObject;
import com.hundsun.aitest.common.ApiPlatformConfig;
import com.hundsun.aitest.service.YApiOperationService;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.net.HttpCookie;
import java.util.*;

@Slf4j
@Data
@Service
public class YApiOperationServiceImpl implements YApiOperationService {

    private String baseUrl;

    private String email;

    private String password;
    private Integer serviceId;

    @Autowired
    private ApiPlatformConfig apiPlatformConfig;

    private Map<String, Integer> services = new HashMap<>();

    private Map<String, String> headers = new HashMap<>();
    private Map<Integer, String> catMap = new HashMap<>();

    @Override
    public void setInitParams(String project){
        this.baseUrl = apiPlatformConfig.getApiPlatform().get(project).getBaseUrl();
        this.email = apiPlatformConfig.getApiPlatform().get(project).getEmail();
        this.password = apiPlatformConfig.getApiPlatform().get(project).getPassword();
        this.serviceId = Integer.valueOf(apiPlatformConfig.getApiPlatform().get(project).getServiceId());
    }

    public void loginPlat(){
        // 服务信息
        services.put("amlps", 333);
        services.put("amlwl", 415);
        String login_url = this.baseUrl +"/api/user/login";
        headers.put("Content-Type", "application/json; charset=utf-8");
        headers.put("cookie", "");
        // 请求参数
        Map<String, Object> params = new HashMap<>();
        params.put("email", this.email);
        params.put("password", this.password);
        log.info("YApiPlat login params: {}", params);
        // 发送请求
        HttpResponse response = HttpRequest.post(login_url)
                .addHeaders(this.headers)
                .body(JSONObject.toJSONString(params)).execute();
        String responseBody = response.body();
        log.info("login response: {}", responseBody);
        HttpCookie yApi_token = response.getCookie("_yapi_token");
        this.headers.replace("cookie", "_yapi_token=" + yApi_token.getValue());
        log.info("login responseBody : " + responseBody);
        log.info("http headers : " + this.headers);
    }

    public void getCatList(){
        // Integer projectId = this.services.get(server);
        String cat_url = this.baseUrl +"/api/project/get?id=" + this.serviceId;
        // 发送请求
        HttpResponse response = HttpRequest.get(cat_url)
                .addHeaders(this.headers).execute();
        String getResponse = response.body();
        log.info("cat response : " + getResponse);
        JSONObject jsonObject = JSONObject.parseObject(getResponse);
        List<Map> catList = jsonObject.getJSONObject("data").getJSONArray("cat").toJavaList(Map.class);
        log.info("cat raw list : " + catList);
        for (Map map : catList) {
            this.catMap.put((Integer) map.get("_id"), (String) map.get("name"));
        }
        log.info("cat res list : " + this.catMap);
    }

    /**
     * 获取接口列表
     */
    public List<String> getInterfaceList(){
        // Integer projectId = this.services.get(server);
        String interface_url = this.baseUrl +"/api/interface/list?page=1&limit=100&project_id=" + this.serviceId;
        // 发送请求
        HttpResponse response = HttpRequest.get(interface_url)
                .addHeaders(this.headers).execute();
        String getResponse = response.body();
        JSONObject jsonObject = JSONObject.parseObject(getResponse);
        List<Map> interfaceList = jsonObject.getJSONObject("data").getJSONArray("list").toJavaList(Map.class);
        interfaceList.sort(Comparator.comparing(m -> (Integer) m.get("catid")));
        log.info("interface list : " + interfaceList);
        List<String> interfaceInfoList = new ArrayList<>();
        for (Map map : interfaceList) {
            Integer catId = (Integer) map.get("catid");
            String catName = this.catMap.get(catId);
            String title = map.get("title").toString();
            String path = map.get("path").toString();
            String interfaceId = map.get("_id").toString();
            String interfaceName = interfaceId + "&" + catName + "-" + title + "&" + path;
            interfaceInfoList.add(interfaceName);
        }
        log.info("interfaceInfoList : " + interfaceInfoList);
        return interfaceInfoList;
    }


    public JSONObject getInterfaceParams(Integer id){
        String interface_url = this.baseUrl + "/api/interface/get?id=" + id;
        // 发送请求
        HttpResponse response = HttpRequest.get(interface_url)
                .addHeaders(this.headers).execute();
        String getResponse = response.body();
        System.out.println("interface info : " + getResponse);
        JSONObject jsonObject = JSONObject.parseObject(getResponse);
        return jsonObject.getJSONObject("data");
    }
}
